package 首尾哨兵;

import java.util.Iterator;

public class Node1 implements Iterable<Integer>{
    @Override
    public Iterator<Integer> iterator() {
        return new Iterator<Integer>() {
            Node p=head;
            @Override
            public boolean hasNext() {
                return p!=tail;
            }

            @Override
            public Integer next() {
                int value=p.value;
                p=p.next;
                return value;
            }
        };
    }

    static class Node{
        Node next;
        Node pre;
        int value;
        public Node(Node pre,int value,Node next){//传参
            this.pre=pre;
            this.value=value;
            this.next=next;
        }
    }
    Node head;
    Node tail;
    public Node1(){//给头尾哨兵赋值
        head=new Node(null,666,null);
        tail=new Node(null,666,null);
        head.next=tail;
        tail.pre=head;
    }
   public Node findNode(int index){
        int i=-1;
        for(Node p=head;p!=tail;p=p.next,i++){
            if(i==index){
                return p;
            }
        }
        return null;
    }
    public void insert(int index,int value) {
        Node prer = findNode(index - 1);
        if (prer == null) {
            throw new IllegalArgumentException(
                    String.format(" 不合法")
            );
        }
        Node nexted=prer.next;
        Node inserted=new Node(prer,value,nexted);
        prer.next=inserted;
        nexted.pre=inserted;
    }
    public void loop(){
        Node p=head;
        while (p!=tail.next){
            System.out.println(p.value);
            p=p.next;
        }
    }
    public void remove(int index) throws Exception {
        Node pre=findNode(index-1);
        if(pre==null){
            throw illegalIndex(index);
        }
        Node removed=pre.next;
        if(removed==tail){
            throw illegalIndex(index);//抛出不合法
        }
        Node nexted=removed.next;
        pre.next=nexted;
        nexted.pre=pre;
    }
    public void addLast(int value){
        Node last=tail.pre;
        Node add=new Node(last,value,tail);
        last.next=add;
        tail.pre=add;
    }
    public void removeLast(){
        Node removed=tail.pre;
        if(removed==tail){
            throw new IllegalArgumentException(
                    String.format("不合法")
            );
        }
        Node pre=removed.pre;
        pre.next=tail;
        tail.pre=pre;
    }
    private Exception illegalIndex(int index) {
        throw new IllegalArgumentException(
                String.format(" 不合法")
        );
    }
}
